<?php
/*
 * @Author: 偻儸小卒[EdisonLiu_]
 * @Date: 2021-07-10 16:15:31
 * @LastEditors: 偻儸小卒[EdisonLiu_]
 * @LastEditTime: 2021-07-12 09:39:03
 * @Description: 
 */

namespace App\Http\Controllers\Traits;

use Illuminate\Support\Facades\Cache;

trait DingDingTrait
{
	// public $config = [
	// 	'app_key' => env('dding_app_key'),
	// 	'app_secret' => env('dding_app_secret'),
	// 	'agent_id' => env('dding_agent_id'),
	// 	'corp_id' => env('dding_corp_id')
	// ];
	private  static function getConfig()
	{
		return getDDingSetting();
	}
	// code置换为用户信息
	private static function getCodeToUser($code)
	{
		$access_token = self::getAccessToken();
		if (!is_string($access_token)) {
			return $access_token;
		}
		$c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET, \DingTalkConstant::$FORMAT_JSON);
		$req = new \OapiUserGetuserinfoRequest();
		$req->setCode($code);
		$resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/user/getuserinfo");

		return $resp;
	}

	// 获取access_token，并缓存起来（缓存周期为钉钉给的期限）
	public static function getAccessToken()
	{
		date_default_timezone_set('Asia/Shanghai');
		$config = self::getConfig();
		$access_token = Cache::get("dingding_{$config['app_key']}_access_token");
		// $access_token='';
		if (empty($access_token)) {
			$c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET, \DingTalkConstant::$FORMAT_JSON);
			$req = new \OapiGettokenRequest();
			$req->setAppkey($config['app_key']);
			$req->setAppsecret($config["app_secret"]);
			$resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/gettoken");
			if ($resp != null && $resp->errcode == '0') {
				$access_token = $resp->access_token;
				Cache::put("dingding_{$config['app_key']}_access_token", $access_token,(($resp->expires_in-60) /60 )); //7140秒转 119分钟 laravel cache 时间是按分钟算的，钉钉官方给的是秒，所以这里有点坑
			} else {
				return $resp;
			}
		}
		// dd($access_token,Cache::has("dingding_{$config['app_key']}_access_token"));
		
		return $access_token;
	}
	// 文件目录转媒体id（类似公众号的媒体id那种）
	public static function getMediaByFile($fileLocation)
	{
		$access_token = self::getAccessToken();

		$c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_POST, \DingTalkConstant::$FORMAT_JSON);
		$req = new \OapiMediaUploadRequest();
		$req->setType("image");
		$req->setMedia($fileLocation);
		$resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/media/upload");
		if ($resp != null) {
			return $resp->media_id;
		} else {
			return null;
		}
	}
	// 获取api的ticket
	public static function getJsapiTicket()
	{
		$access_token = self::getAccessToken();
		$c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET, \DingTalkConstant::$FORMAT_JSON);
		$req = new \OapiGetJsapiTicketRequest();
		$resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/get_jsapi_ticket");
		
		if ($resp != null && $resp->errcode == '0') {
			return $resp->ticket;
		} else {
			return $resp;
		}

		
	}
	// 将ticket等信息转换为参数并返回
	public static function getJsApiConf($url = null)
	{
		$config = self::getConfig();
		$url = ($url == null || $url == '') ? self::curPageURL() : $url;
		$jsapiTicket = self::getJsapiTicket();
		if (!is_string($jsapiTicket)) {
			return $jsapiTicket;
		}
		$config["time_stamp"] =time();

		$signature = self::sign($jsapiTicket, $config["nonce_str"], $config["time_stamp"], $url);
		return [
			'agent_id'=>$config["agent_id"],
			// 'app_key'=>$config["app_key"],
			// 'app_secret'=>$config["app_secret"],
			'corp_id'=>$config["corp_id"],
			'time_stamp'=>$config["time_stamp"],
			'nonce_str'=>$config["nonce_str"],
			'signature'=>$signature
		];
	}

	// 签名
	public static function sign($ticket, $nonceStr, $timeStamp, $url)
	{
		$plain = 'jsapi_ticket=' . $ticket . '&noncestr=' . $nonceStr . '&timestamp=' . $timeStamp . '&url=' . $url;
		return sha1($plain);
	}
	// https转换
	public static function curPageURL()
	{
		$pageURL = 'http';

		if (array_key_exists('HTTPS', $_SERVER) && $_SERVER["HTTPS"] == "on") {
			$pageURL .= "s";
		}
		$pageURL .= "://";

		if ($_SERVER["SERVER_PORT"] != "80") {
			$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
		} else {
			$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
		}
		return $pageURL;
	}
}
